<?php

namespace App\Services\Admin;

use App\Models\Coupon as CouponModel;
use App\Models\UserCouponRecord;

class Coupon extends Base
{
    public static function lists()
    {
        $input = request()->all();

        $where = [];

        if(!empty($input['start_time']) && !empty($input['end_time'])){
            $where[] = ['expiration_time','>=',$input['start_time']];
            $where[] = ['expiration_time','<=',$input['end_time']];
        }

        if(!empty($input['is_opend'])){
            $where[] = ['is_opend', $input['is_opend']];
        }

        if(!empty($input['sear_value'])){
            $where[] = ['coupon_code','like', $input['sear_value']];
        }

        return CouponModel::with(['store'])->whereHas('store',function ($query)use($input){
            if(!empty($input['store_id'])){
                $query->where('id',$input['store_id']);
            }
        })->where($where)->orderBy('id', 'desc');
    }

    public static function info($id)
    {
        return (new CouponModel)->where('id', $id)->first();
    }

    public static function add($param = [])
    {
        $data = (new CouponModel);
        foreach ($param as $k=>$v){
            $data->$k = $v;
        }
        return $data->save();
    }

    public static function edit($id , $param=[])
    {
        return (new CouponModel)->where('id',$id)->update($param);
    }

    public static function del($id)
    {
        return (new CouponModel)->where('id', $id)->delete();
    }

    public static function user_coupon_record($id)
    {
        return UserCouponRecord::where('coupon_id', $id);
    }
}
